package Work;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
 * 
 * @author Lizeth Cuellar
 *
 */
public class Test {
	//	C:\Users\andrea\Desktop\First.xml
	/**
	 * 
	 */
	DocumentBuilderFactory factory;
	DocumentBuilder db;
	Document doc;
	/**
	 * 
	 * @param address
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public Test(String address) throws ParserConfigurationException, SAXException, IOException{
		factory= DocumentBuilderFactory.newInstance();
		db=factory.newDocumentBuilder();
		doc=db.parse(new File(address));
	}
	/**
	 * 
	 */
	public void readXml(){
		Node children = doc.getChildNodes().item(0); 
		Element rootElement = doc.createElement(children.getNodeName());
		children(children, rootElement);
	}
	/**
	 * 
	 * @param nodo1
	 * @param root
	 */
	public void children(Node nodo1, Element root){
		int cont=0;
		NodeList children=nodo1.getChildNodes();
		for(int i=0;i<children.getLength();i++){ 
			Node nodo = children.item(i);	
			if(nodo.getNodeType()==Node.ELEMENT_NODE ) {
				System.out.println(nodo.getParentNode().getNodeName()+" ... root... "+root.getNodeName());
				if((nodo.getParentNode().getNodeName()).equals(root.getNodeName())==false){
					nodo1.removeChild(nodo);
				}
				if(nodo.hasChildNodes()){
					children(nodo, root);
				}
			}
			cont++;
		}
	}
	/**
	 * 
	 */
	public void createXml(){
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer;
		try {
			transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File("C:/Users/andrea/Desktop/Resultfile.xml"));
			transformer.transform(source, result);

			System.out.println("File saved!");
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
